// 主图添加{ bobotitle }

// import { upDataImage } from "@Api/shopsApi"
import {
  Button,
  Icon,
  ImgDefault,
  InputNumber,
  message,
  Modal,
  Popover,
  Radio,
  Slider,
  Space,
  Spin,
  Switch,
  Upload
} from "@bytedance/mona-ui"
import React, { useEffect, useState, useRef, forwardRef, useImperativeHandle } from "react"

import { useAppDispatch, useAppSelector } from "~store"
import { setZhutuAddImageList } from "~store/controller/jinritemaiCopyGoods"

// import { getObjectURL, shuffleArray } from "./copyDataFomate"

import "./index.scss"

import { DndContext, MouseSensor, useSensor, useSensors } from "@dnd-kit/core"
import { arrayMove, SortableContext, useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"

import AiOpenImageComp from "./AIImageComp"
import SetVideoContent from './setVideoContent/item.tsx'

import { upImageItemFunc, getObjectURL, urlToBase64, shuffleArray, compressImage } from './copyDataFomate'


// import { getMateriallistAdmin } from "@Api/webServerApi"
const ossurl = import.meta.env.VITE_PLASMO_PUBLIC_CN_OSS
function getMoveItemInfo(getitrem: number, bi) {
  let mobeInfo = {}
  switch (getitrem) {
    case 1:
      mobeInfo = {
        left: 5,
        top: 5,
        offseX: 5,
        offsetY: 5,
        width: 15,
        height: Math.round(bi * 15)
      }
      break
    case 2:
      mobeInfo = {
        left: 0,
        top: 0,
        offseX: 0,
        offsetY: 0,
        width: 100,
        height: 100
      }
      break
    default:
      break
  }
  return mobeInfo
}
let addTimeData
// 图片组件
const MoveImageBpx = (props: any) => {
  const {
    imageData,
    picImages,
    // setPicWatermark,
    // length,
    setMoterIndex,
    goodsDetellData = {},
    removState,
    onChange
  } = props
  // console.log('goodsDetellData', goodsDetellData)
  if (!imageData) return null
  const dispatch = useAppDispatch()
  const zhutuAddImageList = useAppSelector(
    (state) => state.jinritemaiCopyGoods.zhutuAddImageList
  )
  const [imageState, setImageState] = useState(imageData)
  const [addIfameStatus, setAddIfameStatus] = useState(false)
  const [setAddInfoData, setAddInfoDataFun] = useState<any>([])
  useEffect(() => {
    if (imageState !== imageData) {
      setImageState(imageData)
    }
  }, [imageData])
  useEffect(() => {
    // console.log('imageState00885214//**-*++-', imageState)

    if (imageState !== imageData) {
      onChange(imageState)
      if (addTimeData) {
        clearTimeout(addTimeData)
        addTimeData = null
      }
      addTimeData = setTimeout(() => {
        const conterData = JSON.parse(JSON.stringify(zhutuAddImageList))
        conterData[setMoterIndex].list[imageState.index] = imageState
        dispatch(setZhutuAddImageList(JSON.parse(JSON.stringify(conterData))))
      }, 150)
      return
    }
  }, [imageState])
  const SetImgContent = () => {
    let tuoconter: any = null

    return (
      <div
        style={{
          width: 200
        }}>
        <span>{picImages.config.selectType === 1 ? "图标" : "边框"}大小：</span>

        <Slider
          defaultValue={imageState.watermark.width}
          max={100}
          min={0}
          onChange={(e) => {
            if (tuoconter) {
              clearTimeout(tuoconter)
              tuoconter = null
            }
            tuoconter = setTimeout(() => {
              imageState.watermark.width = e
              imageState.watermark.height = Math.round(
                imageState.watermark.bi * e
              )
              setImageState({ ...imageState })
            }, 500)
          }}
        />
        <div className="boter">
          <Upload
            btnType="link"
            btnText={
              imageState.watermark.url
                ? `更换${picImages.config.selectType === 1 ? "图标" : "图片"}`
                : `添加${picImages.config.selectType === 1 ? "图标" : "图片"}`
            }
            btnIcon={<AddIcon />}
            maxCount={1}
            showUploadList={false}
            beforeUpload={(file) => {
              const fileType = /\image\/\/*/
              if (fileType.test(file.type)) {
                const imageUrl: any = getObjectURL(file)
                var img = new Image()
                img.src = imageUrl
                img.addEventListener("load", () => {
                  const iw = img.width
                  const ih = img.height
                  const bi = ih / iw
                  imageState.watermark.url = imageUrl
                  imageState.watermark.bi = bi
                  imageState.watermark.height =
                    picImages.config.selectType === 1
                      ? Math.round(bi * imageState.watermark.width)
                      : 100

                  setImageState({ ...imageState })
                })
                return
              }
              message.error("仅支持图片")
            }}
          />
          {imageState.watermark.url && (
            <>
              <Button
                type="link"
                style={{ marginLeft: 8 }}
                onClick={() => {
                  const typeConter = getMoveItemInfo(
                    picImages.config.selectType,
                    imageState.watermark.bi
                  )
                  const touWers = Object.assign(
                    imageState.watermark,
                    typeConter
                  )
                  imageState.watermark = touWers
                  setImageState({ ...imageState })
                }}>
                恢复默认
              </Button>
              <Button
                type="link"
                style={{ marginLeft: 8, color: "red" }}
                onClick={() => {
                  const typeConter = getMoveItemInfo(
                    picImages.config.selectType,
                    imageState.watermark.bi
                  )
                  const touWers = Object.assign(
                    imageState.watermark,
                    typeConter
                  )
                  imageState.watermark = touWers
                  imageState.watermark.url = ""
                  setImageState({ ...imageState })
                }}>
                删除{picImages.config.selectType === 1 ? "图标" : "图片"}
              </Button>
            </>
          )}
        </div>
        {/* <div className="sortDom">
        排序：
        <InputNumber
          showCounter
          max={length}
          defaultValue={imageState.index + 1}
          min={1}
          onChange={(e: any) => {
            imageState.index = e - 1
            setPicWatermark(imageState)
          }}
        />
      </div> */}
      </div>
    )
  }

  const { setNodeRef, listeners, transform, transition } = useSortable({
    id: imageData.id
  })

  const styles: any = {
    transform: CSS.Transform.toString(transform),
    transition: transition,
    zIndex: removState && removState === imageData.id ? 10 : 1,
    position:
      removState && removState === imageData.id ? "relative" : "relative",
    opacity: removState && removState === imageData.id ? 0.5 : 1
  }
  return (
    <>
      <Popover
        placement="top"
        mouseEnterDelay={0.5}
        content={<SetImgContent />}>
        <div className="moverbox" style={styles} ref={setNodeRef}>
          <Space direction="vertical" size={4} align="center">

            <Spin spinning={!!imageState.lodingstatus}>


              <div
                className="seterimage"
                onClick={(e) => {
                  e.stopPropagation()
                }}
                onMouseMove={(e: any) => {
                  if (imageState?.watermark.moveStatus) {
                    const distanceX = e.pageX - imageState.watermark.pageX
                    const distanceY = e.pageY - imageState.watermark.pageY
                    imageState.watermark.left = Math.round(
                      imageState.watermark.offseX + distanceX
                    )
                    imageState.watermark.top = Math.round(
                      imageState.watermark.offseY + distanceY
                    )
                    setImageState({ ...imageState })
                  }
                }}>
                {/* <img src={imageState.url} className="couyimage" /> */}
                <ImgDefault
                  // style={{ width: 160, height: 160 }}
                  className="couyimage"
                  imgSrc={(() => {
                    const geturls = JSON.parse(JSON.stringify(imageState))
                    if (geturls.url.indexOf("blob") > -1) {
                      return geturls.url
                    }

                    const imgae = geturls.url?.replace("obj/", "")
                    return imgae + "~110x110_q75.image"
                  })()}
                  mask={false}
                />
                {imageState.watermark?.url && (
                  <img
                    src={imageState.watermark.url}
                    alt="water"
                    draggable="false"
                    style={{
                      width: imageState.watermark.width + "px",
                      height: imageState.watermark.height + "px",
                      top: imageState.watermark.top + "px",
                      left: imageState.watermark.left + "px"
                    }}
                    onMouseDown={(e: any) => {
                      imageState.watermark.moveStatus = false
                      imageState.watermark.setImageStatus = false
                      imageState.watermark.moveStatus = true
                      imageState.watermark.pageX = e.pageX
                      imageState.watermark.pageY = e.pageY
                      imageState.watermark.offseX = e.target.offsetLeft
                      imageState.watermark.offseY = e.target.offsetTop
                      imageState.watermark.clickTime = new Date().getTime()
                      setImageState({ ...imageState })
                    }}
                    onMouseUp={(e: any) => {
                      imageState.watermark.moveStatus = false
                      const upTime = new Date().getTime()
                      if (upTime - imageState.watermark.clickTime < 100) {
                        imageState.watermark.setImageStatus =
                          !imageState.watermark.setImageStatus
                      }
                      setImageState({ ...imageState })
                    }}
                    className="wterioconbos"
                  />
                )}
              </div>
            </Spin>
            <Button
              size="mini"
              style={{
                width: "100px"
              }}
              onClick={() => {
                setAddIfameStatus(true)
                // 入库数据
                setAddInfoDataFun([
                  [
                    {
                      url: imageState.url,
                      index: 0,
                      priindex: 0
                    }
                  ]
                ])
              }}>
              AI作图
            </Button>
          </Space>
          <div className="moveIcon" {...listeners}>
            <Icon type="ServiceMarketIcon"></Icon>
          </div>
        </div>
      </Popover>

      <AiOpenImageComp
        visible={addIfameStatus}
        onCancel={() => setAddIfameStatus(false)}
        type="4"
        setAddInfoData={setAddInfoData}
        product_id={goodsDetellData.product_id}
        img_format={1}
        onChangeImage={(data) => {
          // console.log('datadatadatadata0000', data)
          if (data && data[0]) {
            if (data[0][0] && data[0][0].res_url) {
              setImageState({ ...imageState, url: data[0][0].res_url })
            }
          }
          setAddIfameStatus(false)
        }}></AiOpenImageComp>
    </>
  )
}

const { AddIcon, FinishIcon } = Icon
const AddBodersContent = (props: any, ref: any) => {
  if (!props) return null
  const { goodsDetellData, copyGoodConfig } = props

  if (!goodsDetellData) return
  const { copynum } = copyGoodConfig

  const dispatch = useAppDispatch()
  // 转化图片列表数据
  function getPricImageInfo(moveinfo: any) {
    const picImages =
      goodsDetellData?.pic?.map((res: any, index: number) => {
        return {
          id: index + 1,
          url: res,
          watermark: {
            ...moveinfo,
            bi: 0,
            pageX: 0,
            pageY: 0,
            url: null,
            moveStatus: false,
            clickTime: 0,
            setImageStatus: false,
            mergeurl: null
          },
          moveImageStatus: false,
          translateX: index * 120,
          left: 0,
          top: 0,
          pageX: 0,
          pageY: 0,
          zIndex: 1,
          elemCenterPx: 0,
          index,
          worderker: true
        }
      }) || []
    return picImages
  }
  const zhutuImageList: any = useAppSelector(
    (state) => state.jinritemaiCopyGoods.zhutuImageList
  )
  function addimageList(type) {
    let forList: any[] = []
    for (let i = 0; i < copynum; i++) {
      forList.push(addImageItem(type))
    }
    return forList
  }
  function addImageItem(type) {
    return {
      config: {
        selectType: type
      },
      list: getPricImageInfo(getMoveItemInfo(type, 0))
    }
  }
  const [picImageList, setPicImageList] = useState<any[]>(addimageList(2))
  useEffect(() => {
    dispatch(
      setZhutuAddImageList(
        JSON.parse(
          JSON.stringify(
            picImageList.map((items) => {
              items.list.forEach((iyer, index) => {
                iyer.index = index
              })
              return items
            })
          )
        )
      )
    )
  }, [picImageList])

  const [showImageKu, setShowImageKu] = useState(false)
  const [addWorker, setAddWorker] = useState(true)
  const [selectImages, setSelectImages] = useState<any[]>(
    zhutuImageList.map((res) => {
      // console.log('边框', res)

      return {
        select: false,
        url: import.meta.env.VITE_PLASMO_PUBLIC_CN_OSS + res
        // url: 'https://wtplug.oss-cn-hangzhou.aliyuncs.com/' + res
      }
    })
  )
  const [seleCtcontenrIndex, setSeleCtcontenrIndex] = useState(-1)
  const [addImageberderLodin, setAddimageLodin] = useState(false)
  useEffect(() => {
    if (picImageList.length === copynum) return
    const addConter = copynum - picImageList.length
    if (addConter > 0) {
      for (let i = 0; i < addConter; i++) {
        picImageList.push(addImageItem(2))
      }
    } else {
      picImageList.splice(addConter, Math.abs(addConter))
    }
    setPicImageList([...picImageList])
  }, [copynum])
  const [addIfameStatus, setAddIfameStatus] = useState(false)
  const [lodinIframe, setLodinIframe] = useState(true)
  // let setAddInfoData = []
  const [setAddInfoData, setSetAddInfoData] = useState<any[]>([])
  // console.log('picImageList', picImageList)

  const videoRefs = useRef<any>([])
  useImperativeHandle(ref, () => ({
    videoRefsDatas() {
      return videoRefs
    }
  }))
  // useImperativeHandle(ref, () => ({
  //   videoRefsDatas() {
  //     return videoRefs
  //   }
  // }))
  return (<div style={{ marginLeft: 25 }}>
    <Space direction="vertical">
      {false && (<Button
        type="primary"
        disabled={picImageList.length >= copyGoodConfig.copynum}
        size="mini"
        onClick={() => {
          picImageList.push({
            config: {
              selectType: 2
            },
            list: getPricImageInfo(getMoveItemInfo(1, 0))
          })
          setPicImageList([...picImageList])
        }}>
        添加图片组
      </Button>)}
      <div className="imsgecontenbo">
        <Space direction="vertical">
          <div className="sye" style={{
            color: "#000",
            fontSize: 14,
            fontWeight: 900
          }}>批量调整</div>

          <Space>
            <Button
              size="mini"
              onClick={() => {
                const assetAddInfoData = picImageList.map(
                  (res: any, priindex) => {
                    // res.list = shuffleArray(res.list)
                    return res.list.map((itewms: any, index) => {
                      // itewms.index = index
                      return { url: itewms.url, index, priindex }
                    })
                  }
                )
                // console.log('setAddInfoData', assetAddInfoData)
                setSetAddInfoData([...assetAddInfoData])
                setAddIfameStatus(true)
              }}>
              批量AI作图(全部主图)
            </Button>
            <div
              className="p1ad"
              style={{
                fontWeight: 600,
                color: "#bdb5228d"
              }}>
              AI限时免费体验
            </div>
            <Button
              type="link"
              className="conetrs"
              onClick={() => {
                picImageList.forEach((res: any) => {
                  res.list = shuffleArray(res.list)
                  res.list.forEach((itewms: any, index) => {
                    itewms.index = index
                  })
                })
                setPicImageList([...picImageList])
              }}>
              打乱全部主图
            </Button>
            <Button
              type="link"
              className="conetrs"
              onClick={() => {
                setSeleCtcontenrIndex(-2)
                setShowImageKu(true)
              }}>
              批量添加边框
            </Button>
            <Space size={2}>
              <Switch
                checked={addWorker}
                size="small"
                onChange={(e) => {
                  // console.log("e", e, picImageList)
                  picImageList.forEach((res: any) => {
                    res.list &&
                      res.list.forEach((items: any) => {
                        items.worderker = e
                      })
                  })
                  setPicImageList([...picImageList])
                  setAddWorker(e)
                }}
              />
              添加主图水印
              <Popover
                content={
                  <Space direction="vertical" align="center">
                    <ImgDefault
                      imgSrc={
                        ossurl +
                        "funsaction/convert/whertPPt.png?x-oss-process=image/resize,h_300,m_lfit"
                      }
                      width="300px"
                      height="300px"
                      borderRadius={0}></ImgDefault>
                    将在主图右下角添加随机字母水印
                  </Space>
                }>
                <Icon type="DoubtIcon"></Icon>
              </Popover>
            </Space>
          </Space>
        </Space>
      </div>
      {...picImageList.map((picImages, indexbser) => {
        return (
          <div className="imsgecontenbo" key={indexbser}>
            <Space direction="vertical">
              <div className="conetr">主图 {indexbser + 1}</div>
              <Radio.Group
                value={picImages.config.selectType}
                onChange={(e) => {
                  picImages.config.selectType = e.target.value * 1
                  picImages.list = JSON.parse(
                    JSON.stringify(
                      getPricImageInfo(getMoveItemInfo(e.target.value * 1, 0))
                    )
                  )
                  setPicImageList([...picImageList])
                }}>
                <Radio value={2}>
                  添加边框{" "}
                  <Button
                    disabled={picImages.config.selectType === 1}
                    type="link"
                    onClick={() => {
                      setSeleCtcontenrIndex(indexbser)
                      // getMateriallistAdmin({
                      //   type: 1,
                      //   page: 1,
                      //   pageSize: 20
                      // }).then((res) => {
                      //   console.log('res边框', res)
                      // })
                      return setShowImageKu(true)
                    }}>
                    边框库
                  </Button>
                </Radio>
                <Radio value={1}>添加图标</Radio>
              </Radio.Group>
              <Space size={20}>
                <div className="conternotoue">
                  <div className="topmovuerfoter">
                    <RomoItemBox
                      data={picImages.list}
                      onChange={(e) => {
                        // console.log("ee", e)
                        picImages.list = e
                        setPicImageList([...picImageList])
                      }}
                      goodsDetellData={goodsDetellData}
                      picImages={picImages}
                      setMoterIndex={indexbser}></RomoItemBox>
                    {/* {...picImages.list.map((res: any, index: number) => {
                      return (
                        <MoveImageBpx
                          setMoterIndex={indexbser}
                          imageData={res}
                          key={index}
                          picImages={picImages}
                          length={picImages.list.length}
                          goodsDetellData={goodsDetellData}
                          setPicWatermark={(e) => {
                            const arrMap = new Array(picImages.list.length)
                            arrMap[e.index] = picImages.list[index]
                            picImages.list.splice(index, 1)
                            const sortdate = picImages.list.sort(
                              (a, b) => a.index - b.index
                            )
                            for (let i = 0; i < arrMap.length; i++) {
                              if (!arrMap[i]) {
                                const inputdata = sortdate.splice(0, 1)
                                arrMap[i] = inputdata[0]
                              }
                            }
                            arrMap.forEach((mpi, indexer) => {
                              mpi.index = indexer
                              mpi.translateX = indexer * 120
                            })
                            picImages.list = arrMap
                            setPicImageList([...picImageList])
                          }} />
                      )
                    })} */}
                  </div>
                  <SetVideoContent
                    goodsDetellData={goodsDetellData}
                    copyGoodConfig={copyGoodConfig}
                    picImages={picImages.list}
                    ref={(el) => {
                      if (el) {
                        videoRefs.current[indexbser] = el
                      }
                      // if(el)
                    }}
                  ></SetVideoContent>
                  <div>
                    <Space>
                      <Button type="secondary" icon={<Icon type="GalleryIcon"></Icon>} onClick={() => {
                        // 打开文件选择器
                        const input = document.createElement('input');
                        input.type = 'file';
                        input.multiple = true;
                        input.accept = 'image/*';
                        input.onchange = async (event) => {
                          const files = event.target.files;
                          const imageList = []
                          for (let i = 0; i < files.length; i++) {
                            const imageUrl: any = getObjectURL(files[i])
                            imageList.push(imageUrl)
                          }


                          // 压缩图片
                          const getIyer = imageList.splice(0, 5)

                          getIyer.forEach((item, index) => {
                            if (!picImages.list[index]) {
                              picImages.list[index] = JSON.parse(JSON.stringify(picImages.list[0]))
                            }
                            picImages.list[index].url = item
                            picImages.list[index].lodingstatus = true
                          })
                          for (let i = 0; i < picImages.list.length; i++) {
                            picImages.list[i].id = i + 1
                          }
                          setPicImageList([...picImageList])

                          const compressedImages = await Promise.all(getIyer.map(async (image, indexser) => {
                            const compressedImage = await compressImage(image, 1, 800, 800);
                            upImageItemFunc(compressedImage).then((res) => {
                              picImages.list[indexser].url = res.data[0]
                              picImages.list[indexser].lodingstatus = false
                              // picImages.list[indexbser].lodingstatus = false
                              setPicImageList([...picImageList])
                            })
                            return compressedImage;
                          }))
                          console.log('compressedImages', compressedImages)
                          // console.log('getIyer', getIyer)

                        }
                        input.click();

                      }}>批量替换主图</Button>
                      <Button
                        onClick={() => {
                          setAddIfameStatus(true)
                          const assetAddInfoData = picImageList.map(
                            (res: any, priindex) => {
                              // res.list = shuffleArray(res.list)
                              return res.list.map((itewms: any, index) => {
                                // itewms.index = index
                                return {
                                  url:
                                    priindex === indexbser ? itewms.url : "",
                                  index,
                                  priindex
                                }
                              })
                            }
                          )
                          // console.log('setAddInfoData', assetAddInfoData)
                          setSetAddInfoData([...assetAddInfoData])
                          setAddIfameStatus(true)
                        }}>
                        批量AI作图
                      </Button>
                      <Upload
                        btnText={`上传${picImages.config.selectType === 1 ? "图标" : "边框"}`}
                        btnType="default"
                        btnIcon={<AddIcon />}
                        maxCount={1}
                        showUploadList={false}
                        beforeUpload={(file) => {
                          const fileType = /\image\/\/*/
                          if (fileType.test(file.type)) {
                            const imageUrl = getObjectURL(file)
                            var img: any = new Image()
                            img.src = imageUrl
                            img.addEventListener("load", () => {
                              const iw = img.width
                              const ih = img.height
                              const bi = ih / iw
                              picImages.list.forEach((picItem) => {
                                picItem.watermark.url = imageUrl
                                picItem.watermark.bi = bi
                                picItem.watermark.height =
                                  picImages.config.selectType === 1
                                    ? Math.round(bi * picItem.watermark.width)
                                    : 100
                              })
                              setPicImageList([...picImageList])
                            })
                            return
                          }
                          message.error("仅支持图片")
                        }}
                      />
                      {/* <Button type="link">历史{picImages.config.selectType === 1 ? '图标' : '边框'}</Button> */}
                      <Button
                        type="link"
                        onClick={() => {
                          picImages.list.forEach((item) => {
                            const infodater = getMoveItemInfo(
                              picImages.config.selectType,
                              item.watermark.bi
                            )
                            const mergewet = Object.assign(
                              item.watermark,
                              infodater
                            )
                            item.watermark = mergewet
                          })
                          setPicImageList([...picImageList])
                        }}>
                        恢复默认
                      </Button>
                      <Button
                        type="link"
                        onClick={() => {
                          picImages.list.forEach((picItem) => {
                            picItem.watermark.url = null
                            picItem.watermark.bi = 0
                            picItem.watermark.height = 0
                          })
                          setPicImageList([...picImageList])
                        }}>
                        清除所有
                        {picImages.config.selectType === 1 ? "图标" : "边框"}
                      </Button>
                      {picImages.config.selectType === 2 && (
                        <Button
                          type="link"
                          onClick={() => {
                            setSeleCtcontenrIndex(indexbser)
                            // getMateriallistAdmin({
                            //   type: 1,
                            //   page: 1,
                            //   pageSize: 20
                            // }).then((res) => {
                            //   console.log('res边框', res)
                            // })
                            return setShowImageKu(true)
                          }}>
                          {picImages.config.selectType === 1 ? "图标" : "边框"}库
                        </Button>
                      )}
                      {/* <Button type="link" onClick={() => mergeImageFun(picImages)}>
                        测试合成图片
                      </Button> */}
                      <Button
                        type="link"
                        onClick={() => {
                          picImages.list = shuffleArray(picImages.list)
                          picImages.list.forEach((item, index) => {
                            item.index = index
                          })
                          // picImages.list.forEach((item) => {
                          //   const infodater = getMoveItemInfo(
                          //     picImages.config.selectType,
                          //     item.watermark.bi
                          //   )
                          //   const mergewet = Object.assign(item.watermark, infodater)
                          //   item.watermark = mergewet
                          // })
                          setPicImageList([...picImageList])
                        }}>
                        打乱主图顺序
                      </Button>

                    </Space>
                  </div>
                </div>
                <div className="deletcontenty">
                  {false && (
                    <Icon
                      type="DeleteIcon"
                      onClick={() => {
                        if (picImageList.length === 1) {
                          return message.warning("至少保留一个")
                        }
                        picImageList.splice(indexbser, 1)
                        setPicImageList([...picImageList])
                      }}></Icon>
                  )}
                </div>
              </Space>
            </Space>
          </div>
        )
      })}
    </Space>
    <Modal
      width={675}
      visible={showImageKu}
      title={`选择边框 ${seleCtcontenrIndex === -2
        ? `(${selectImages.filter((item) => item.select).length
        }/${copynum}) ${selectImages.filter((item) => item.select).length >= copynum
          ? "(已选完)"
          : ""
        }`
        : ""
        }`}
      okText=" 确定"
      cancelText=" 取消"
      onCancel={() => {
        setShowImageKu(false)
        setAddimageLodin(false)
        selectImages.forEach((item) => {
          item.select = false
        })
        setSelectImages([...selectImages])
      }}
      onOk={() => {
        if (seleCtcontenrIndex !== -2) {
          const isSelectImageItem = selectImages.find((si) => si.select)
          // const imageUrl = getObjectURL(file)
          var img: any = new Image()
          img.src = isSelectImageItem.url
          img.addEventListener("load", () => {
            const iw = img.width
            const ih = img.height
            const bi = ih / iw
            picImageList[seleCtcontenrIndex].list.forEach((picItem) => {
              picItem.watermark.url = isSelectImageItem.url
              picItem.watermark.bi = bi
              picItem.watermark.height =
                picImageList[seleCtcontenrIndex].config.selectType === 1
                  ? Math.round(bi * picItem.watermark.width)
                  : 100
            })
            setPicImageList([...picImageList])
            setAddimageLodin(false)
          })
          setShowImageKu(false)
          // selectImages.forEach((item) => {
          //   item.select = false
          // })
          setSelectImages([...selectImages])
          return
        }
        setAddimageLodin(true)

        const selectIImages = selectImages.filter((item) => item.select)
        let cbIndex = 0
        addImgaesar(selectIImages, () => {
          setShowImageKu(false)
          selectImages.forEach((item) => {
            item.select = false
          })
          setAddimageLodin(false)
          setSelectImages([...selectImages])
        })
        function addImgaesar(selectItem, cb) {
          if (!selectItem.length) {
            return cb && cb()
          }

          const aselectier = selectItem.splice(0, 1)
          var img: any = new Image()
          img.src = aselectier[0].url
          img.addEventListener("load", () => {
            const iw = img.width
            const ih = img.height
            const bi = ih / iw
            picImageList[cbIndex].config.selectType = 2
            picImageList[cbIndex].list.forEach((picItem) => {
              const typeConter = getMoveItemInfo(2, bi)
              const touWers = Object.assign(picItem.watermark, typeConter)
              picItem.watermark = touWers
              picItem.watermark.url = aselectier[0].url
              picItem.watermark.bi = bi
              picItem.watermark.height =
                picImageList[cbIndex].config.selectType === 1
                  ? Math.round(bi * picItem.watermark.width)
                  : 100
            })
            setPicImageList([...picImageList])
            cbIndex++
            addImgaesar(selectItem, cb)
          })
        }
      }}>
      <Spin spinning={addImageberderLodin}>
        <div className="selectListerimgae">
          {selectImages.map((res: any, index: number) => {
            return (
              <div className="contr" key={index}>
                <img
                  className="imageconer"
                  src={res.url}
                  alt={res.url}
                  onClick={() => {
                    if (seleCtcontenrIndex !== -2) {
                      selectImages.forEach((item) => {
                        item.select = false
                      })
                      res.select = true
                      setSelectImages([...selectImages])
                      return
                    }
                    const selectLength = selectImages.filter(
                      (item) => item.select
                    ).length
                    // console.log('slectall', seleCtcontenrIndex, copynum)
                    if (res.select) {
                      res.select = false
                      setSelectImages([...selectImages])
                      return
                    }
                    if (selectLength < copynum) {
                      res.select = true
                      setSelectImages([...selectImages])
                      return
                    }
                    message.warning("最多选择" + copynum + "张图片")
                  }}
                />
                {res.select && <FinishIcon className="selectImage" />}
              </div>
            )
          })}
        </div>
      </Spin>
    </Modal>
    <AiOpenImageComp
      visible={addIfameStatus}
      onCancel={() => setAddIfameStatus(false)}
      type="4"
      setAddInfoData={setAddInfoData}
      product_id={goodsDetellData.product_id}
      img_format={1}
      onChangeImage={(data) => {
        data.forEach((item, index) => {
          item.forEach((iyee, its) => {
            if (iyee.res_url) {
              picImageList[iyee.priindex].list[iyee.index].url = iyee.res_url
            }
          })
        })
        setPicImageList([...picImageList])
        setAddIfameStatus(false)
      }}></AiOpenImageComp>
  </div>
  )
}
const RomoItemBox = (props: any) => {
  const { data, onChange, goodsDetellData, picImages, setMoterIndex } = props
  // console.log('chdatas', data)

  let [list, setList] = useState<any[]>(data)
  // console.log('listlistlist', list)
  // if (JSON.stringify(data.sort((a, b) => a.id - b.id)) !== JSON.stringify(list.sort((a, b) => a.id - b.id))) {
  //   setList([...data])
  //   // onChange && onChange(list)
  // }
  useEffect(() => {
    // console.log('修改数据', data.sort((a, b) => a.id - b.id))
    // console.log('修改数据', list.sort((a, b) => a.id - b.id))
    if (
      JSON.stringify(
        JSON.parse(JSON.stringify(data)).sort((a, b) => a.id - b.id)
      ) !==
      JSON.stringify(
        JSON.parse(JSON.stringify(list)).sort((a, b) => a.id - b.id)
      )
    ) {
      list = data
      setList([...list])
      // onChange && onChange(list)
    }
  }, [data])
  useEffect(() => {
    // console.log('data++--***', data, list)
    if (JSON.stringify(data) !== JSON.stringify(list)) {
      // console.log('拖拽状态')
      onChange && onChange(list)
      // setList([...data])
    }
  }, [list])
  const [removState, setRemoveState] = useState(false)
  const sensors = useSensors(
    useSensor(MouseSensor, {
      activationConstraint: {
        distance: 1 // 按住不动移动5px 时 才进行拖拽, 这样就可以触发点击事件
      }
    })
  )
  return (
    <DndContext
      sensors={sensors}
      onDragStart={(e: any) => {
        const { active } = e
        setRemoveState(active.id)
      }}
      onDragEnd={(e) => {
        setRemoveState(false)
        const { active, over } = e
        if (!over || !over.id) return
        let activeIndex
        let overIndex
        list.forEach((val, index) => {
          if (val.id === active.id) {
            activeIndex = index
          }
          if (val.id === over.id) {
            overIndex = index
          }
        })
        setList((items) => {
          const adddata = arrayMove(items, activeIndex, overIndex)
          return adddata
        })
      }}>
      <SortableContext items={[...list]}>
        <div className="topmovuerfoter-tower">
          {list.map((res: any, index: number) => {
            return (
              <MoveImageBpx
                key={res.id}
                imageData={res}
                removState={removState}
                allList={list}
                onChange={(data) => {
                  // console.log('data', data)
                  // console.log('res', res)
                  // res = { ...data }
                  setList((item) => {
                    return item.map((item) => {
                      if (item.id === res.id) {
                        return res
                      } else {
                        return item
                      }
                    })
                    // console.log('item', item)
                    // return [...item]
                  })
                }}
                index={index}
                goodsDetellData={goodsDetellData}
                picImages={picImages}
                setMoterIndex={setMoterIndex}
              />
            )
          })}
        </div>
      </SortableContext>
    </DndContext>
  )
}

export default forwardRef(AddBodersContent)
